{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Title: #Rearrange Spaces Between Words"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Difficulty: #Easy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Category Title: #Algorithms"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Tag Slug: #string"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Name Translated: #字符串"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solution Name: reorderSpaces"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Title: #重新排列单词间的空格"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Content:\n",
    "<p>给你一个字符串 <code>text</code> ，该字符串由若干被空格包围的单词组成。每个单词由一个或者多个小写英文字母组成，并且两个单词之间至少存在一个空格。题目测试用例保证 <code>text</code> <strong>至少包含一个单词</strong> 。</p>\n",
    "\n",
    "<p>请你重新排列空格，使每对相邻单词之间的空格数目都 <strong>相等</strong> ，并尽可能 <strong>最大化</strong> 该数目。如果不能重新平均分配所有空格，请 <strong>将多余的空格放置在字符串末尾</strong> ，这也意味着返回的字符串应当与原 <code>text</code> 字符串的长度相等。</p>\n",
    "\n",
    "<p>返回 <strong>重新排列空格后的字符串</strong> 。</p>\n",
    "\n",
    "<p>&nbsp;</p>\n",
    "\n",
    "<p><strong>示例 1：</strong></p>\n",
    "\n",
    "<pre><strong>输入：</strong>text = &quot;  this   is  a sentence &quot;\n",
    "<strong>输出：</strong>&quot;this   is   a   sentence&quot;\n",
    "<strong>解释：</strong>总共有 9 个空格和 4 个单词。可以将 9 个空格平均分配到相邻单词之间，相邻单词间空格数为：9 / (4-1) = 3 个。\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 2：</strong></p>\n",
    "\n",
    "<pre><strong>输入：</strong>text = &quot; practice   makes   perfect&quot;\n",
    "<strong>输出：</strong>&quot;practice   makes   perfect &quot;\n",
    "<strong>解释：</strong>总共有 7 个空格和 3 个单词。7 / (3-1) = 3 个空格加上 1 个多余的空格。多余的空格需要放在字符串的末尾。\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 3：</strong></p>\n",
    "\n",
    "<pre><strong>输入：</strong>text = &quot;hello   world&quot;\n",
    "<strong>输出：</strong>&quot;hello   world&quot;\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 4：</strong></p>\n",
    "\n",
    "<pre><strong>输入：</strong>text = &quot;  walks  udp package   into  bar a&quot;\n",
    "<strong>输出：</strong>&quot;walks  udp  package  into  bar  a &quot;\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 5：</strong></p>\n",
    "\n",
    "<pre><strong>输入：</strong>text = &quot;a&quot;\n",
    "<strong>输出：</strong>&quot;a&quot;\n",
    "</pre>\n",
    "\n",
    "<p>&nbsp;</p>\n",
    "\n",
    "<p><strong>提示：</strong></p>\n",
    "\n",
    "<ul>\n",
    "\t<li><code>1 &lt;= text.length &lt;= 100</code></li>\n",
    "\t<li><code>text</code> 由小写英文字母和 <code>&#39; &#39;</code> 组成</li>\n",
    "\t<li><code>text</code> 中至少包含一个单词</li>\n",
    "</ul>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Description: [rearrange-spaces-between-words](https://leetcode.cn/problems/rearrange-spaces-between-words/description/)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solutions: [rearrange-spaces-between-words](https://leetcode.cn/problems/rearrange-spaces-between-words/solutions/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_cases = ['\"  this   is  a sentence \"', '\" practice   makes   perfect\"']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        \n",
    "        space = text.count(\" \")\n",
    "        ll = text.split(\" \")\n",
    "        \n",
    "        ln = []\n",
    "        for t in ll:\n",
    "            if t !='':\n",
    "                ln.append(t)\n",
    "        print(ln)\n",
    "        if len(ln)==1:\n",
    "            return ln[0]+space*\" \"\n",
    "        strr = \"\"\n",
    "        strr = str(ln[0])\n",
    "        ss = space//(len(ln)-1)\n",
    "        print(ss)\n",
    "        for i in range(1,len(ln)):\n",
    "            \n",
    "            strr += ss*\" \"\n",
    "            space -= ss\n",
    "            strr += ln[i]\n",
    "        strr += space * \" \"\n",
    "\n",
    "        return strr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        spaces = text.count(' ')\n",
    "        words = text.split()\n",
    "        if len(words) == 1:\n",
    "            return words[0] + ' ' * spaces\n",
    "        else:\n",
    "            space = ' ' * (spaces // (len(words) - 1))\n",
    "            return space.join(words) + ' ' * (spaces % (len(words) - 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        spaceNum = text.count(' ')\n",
    "        words = text.split()\n",
    "        reStr = ''\n",
    "        temp = ''\n",
    "        if spaceNum == 0:\n",
    "            return text \n",
    "        \n",
    "        if len(words) == 1:\n",
    "            return words[0] + ' ' * spaceNum\n",
    "\n",
    "        rest_space = spaceNum % (len(words) - 1)\n",
    "        pre_space = spaceNum // (len(words) - 1)\n",
    "        print(pre_space,rest_space)\n",
    "\n",
    "        spaceNum -= rest_space\n",
    "        for word in words:\n",
    "            if spaceNum >= pre_space:\n",
    "                reStr = reStr + word + ' ' * pre_space\n",
    "                spaceNum -= pre_space\n",
    "            else:\n",
    "                reStr = reStr + word + ' ' * rest_space\n",
    "\n",
    "        return reStr "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        temp1 = sum([1 for c in text if c == \" \"])\n",
    "        temp2 = text.split()\n",
    "        if len(temp2) == 1:\n",
    "            return temp2[0] + temp1 * \" \"\n",
    "        res = ''\n",
    "        for i in range(len(temp2)):\n",
    "            res += temp2[i]\n",
    "            res += \" \" * (temp1 // (len(temp2)-1))\n",
    "        res = res[:-(temp1 // (len(temp2)-1))]\n",
    "        res += (temp1 % (len(temp2)-1)) * \" \"\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        tmp_w = ''\n",
    "        word_list = []\n",
    "        restore_space = ''\n",
    "        for i in text:\n",
    "            if i == ' ':\n",
    "                if tmp_w != '':\n",
    "                    word_list.append(tmp_w)\n",
    "                    tmp_w = ''\n",
    "                restore_space += i\n",
    "            else:\n",
    "                tmp_w += i\n",
    "        if tmp_w != '':\n",
    "            word_list.append(tmp_w)\n",
    "        space_cnt = len(restore_space)\n",
    "        if len(word_list) == 1:\n",
    "            return word_list[0] + restore_space\n",
    "        else:\n",
    "            split_space_num  = space_cnt // (len(word_list) - 1 )\n",
    "            tail_space = space_cnt % (len(word_list) - 1 )\n",
    "            return (' '*split_space_num).join(word_list) + tail_space*' '"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        num = text.count(' ')\n",
    "        l = text.split()\n",
    "        reStr = ''\n",
    "        temp = ''\n",
    "        if num == 0:\n",
    "            return text \n",
    "\n",
    "        if len(l) > 1:\n",
    "            space = int(num / (len(l)-1))\n",
    "        else:\n",
    "            space = num\n",
    "        \n",
    "        for i in range(space):\n",
    "            temp = temp + ' '\n",
    "\n",
    "        \n",
    "        for j in l:\n",
    "            reStr = reStr + j\n",
    "            if num >= space:\n",
    "                reStr += temp\n",
    "                num -= space\n",
    "\n",
    "        if num >= 1:\n",
    "            for k in range(num):\n",
    "                reStr = reStr +' '\n",
    "\n",
    "        return reStr "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        x=collections.Counter(text)\n",
    "        a=x[' '] \n",
    "        s=[i for i in list(text.split(' ')) if len(i)!=0]\n",
    "        b=len(s) \n",
    "        if b==1:\n",
    "            return s[0]+' '*a\n",
    "        else:\n",
    "            n=a//(b-1) \n",
    "            t=[]\n",
    "            for i in range(len(s)):\n",
    "                t.append(s[i])\n",
    "                if i!=len(s)-1:\n",
    "                    t.append(' '*n)\n",
    "                    a-=n\n",
    "                elif a==0:\n",
    "                    continue\n",
    "                else:\n",
    "                    t.append(' '*a)\n",
    "            return ''.join(t)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        c = text.count(\" \")\n",
    "        li = text.strip().split()\n",
    "        if len(li) == 1:\n",
    "            return li[0] + \" \" * c\n",
    "        s, s1 = divmod(c, len(li) - 1) \n",
    "        return (\" \" * s).join(li)  + \" \" * s1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        lt=text.split()\n",
    "        ct=0\n",
    "        for i in text:\n",
    "            if i.isspace():\n",
    "                ct+=1\n",
    "        #print(lt)\n",
    "        if len(lt)==1:\n",
    "            t,y=0,ct\n",
    "        else:\n",
    "            t,y=ct//(len(lt)-1),ct%(len(lt)-1)            \n",
    "        a,b=' ' * t,' '*y\n",
    "        r=a.join(lt) + b\n",
    "        return r"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        space_num = 0  # 空格个数\n",
    "        word_num = 0  # 单词个数\n",
    "        tmp_word = ''  # 储存单词\n",
    "        new_text = ''  # 新字符串\n",
    "        for c in text:\n",
    "            if c == ' ':\n",
    "                space_num += 1\n",
    "                if tmp_word != '':\n",
    "                    new_text += tmp_word\n",
    "                    new_text += ' '\n",
    "                    tmp_word = ''\n",
    "                    word_num += 1\n",
    "            else:\n",
    "                tmp_word += c\n",
    "        \n",
    "        if tmp_word != '':\n",
    "            new_text += tmp_word\n",
    "            new_text += ' '\n",
    "            tmp_word = ''\n",
    "            word_num += 1\n",
    "        \n",
    "        if word_num == 0:\n",
    "            return text\n",
    "        if word_num == 1:\n",
    "            return new_text.strip() + space_num * ' '\n",
    "\n",
    "        a = int(space_num / (word_num - 1))\n",
    "        b = space_num % (word_num - 1)\n",
    "\n",
    "        new_text = new_text.strip().replace(' ', ' '*a) + \" \"*b\n",
    "\n",
    "        return new_text\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        words = text.split()\n",
    "        space = text.count(' ')\n",
    "        if len(words) == 1:\n",
    "            return words[0] + ' ' * space\n",
    "        per_space, rest_space = divmod(space, len(words) - 1)\n",
    "        return (' ' * per_space).join(words) + ' ' * rest_space\n",
    "\n",
    "'''\n",
    "作者：力扣官方题解\n",
    "链接：https://leetcode.cn/problems/rearrange-spaces-between-words/solutions/1805311/zhong-xin-pai-lie-dan-ci-jian-de-kong-ge-5kln/\n",
    "来源：力扣（LeetCode）\n",
    "著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        num = text.count(' ')\n",
    "        l = text.split()\n",
    "        temp = ''\n",
    "        if len(l) > 1:\n",
    "            space = int(num / (len(l)-1))\n",
    "        else:\n",
    "            space = num\n",
    "        \n",
    "        for i in range(space):\n",
    "            temp = temp + ' '\n",
    "\n",
    "        s = ''\n",
    "        for j in l:\n",
    "            s = s + j\n",
    "            if num >= space:\n",
    "                s += temp\n",
    "                num -= space\n",
    "\n",
    "        if num >= 1:\n",
    "            for k in range(num):\n",
    "                s = s +' '\n",
    "\n",
    "        return s "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        return (\" \" * (space // (len(sp) - 1))).join(sp) + \" \" * (space % (len(sp) - 1)) if (space := text.count(\" \")) and len(sp := text.split()) > 1 else (sp[0] + \" \" * space if space else text)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        num = text.count(' ')\n",
    "        l = text.split()\n",
    "        reStr = ''\n",
    "        temp = ''\n",
    "        if num == 0:\n",
    "            return text \n",
    "\n",
    "        if len(l) > 1:\n",
    "            space = int(num / (len(l)-1))\n",
    "        else:\n",
    "            space = num\n",
    "        \n",
    "        for i in range(space):\n",
    "            temp = temp + ' '\n",
    "\n",
    "        \n",
    "        for j in l:\n",
    "            reStr = reStr + j\n",
    "            if num >= space:\n",
    "                reStr += temp\n",
    "                num -= space\n",
    "\n",
    "        if num >= 1:\n",
    "            for k in range(num):\n",
    "                reStr = reStr +' '\n",
    "\n",
    "        return reStr "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        spaceNum = text.count(' ')\n",
    "        words = text.split()\n",
    "        reStr = ''\n",
    "        temp = ''\n",
    "        if spaceNum == 0:\n",
    "            return text \n",
    "        \n",
    "        if len(words) == 1:\n",
    "            return words[0] + ' ' * spaceNum\n",
    "\n",
    "        rest_space = spaceNum % (len(words) - 1)\n",
    "        pre_space = spaceNum // (len(words) - 1)\n",
    "        spaceNum -= rest_space\n",
    "        \n",
    "        for word in words:\n",
    "            if spaceNum >= pre_space:\n",
    "                reStr = reStr + word + ' ' * pre_space\n",
    "                spaceNum -= pre_space\n",
    "            else:\n",
    "                reStr = reStr + word + ' ' * rest_space\n",
    "\n",
    "        return reStr "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        space = text.count(\" \")\n",
    "        words = text.split()\n",
    "        if len(words)>1:\n",
    "            space_num = len(words)-1\n",
    "            space_lth = int(space/space_num)\n",
    "            rest_lth = space-space_lth*space_num\n",
    "        else:\n",
    "            return \" \".join(words)+space*\" \"\n",
    "        tgt = (\" \"*space_lth).join(words)+rest_lth*\" \"\n",
    "        return tgt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        count = text.count(' ')   \n",
    "        list1 =[i for i in text.split(\" \") if i!='']\n",
    "        # print(len(list1))\n",
    "        if len(list1)<=1:\n",
    "            return \"\".join(list1)+count*\" \"\n",
    "        # print(count)\n",
    "        n = len(list1)-1\n",
    "        if count%n==0:\n",
    "            res = (\" \"*(count//n)).join(list1)\n",
    "        else:\n",
    "            res = (\" \"*(count//n)).join(list1) +(count%n)*\" \"\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        n=text.count(' ')\n",
    "        ans=''\n",
    "        word=text.split(' ')\n",
    "        w=[x for x in word if x!='']\n",
    "        total_word=len(w)\n",
    "        if total_word!=1:\n",
    "            blank=n//(total_word-1)\n",
    "            remain=n%(total_word-1)\n",
    "        else:\n",
    "            remain=n\n",
    "        for i in range(total_word):\n",
    "            if i==0:\n",
    "                ans+=w[i]\n",
    "            else:\n",
    "                ans+=' '*blank+w[i]\n",
    "        ans+=' '*remain\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        # 去掉空格，转成列表['this', 'is', 'a', 'sentence']\n",
    "        words=text.split()\n",
    "        # 空格的数量\n",
    "        space=text.count(' ')\n",
    "        # 如果只有一个单词，把空格全加在单词后面就行\n",
    "        if len(words)==1:\n",
    "            return words[0]+\" \"*space\n",
    "        # 如果有多个单词，每个单词平分，多余的放最后\n",
    "        avg=space//(len(words)-1)\n",
    "        rest=space%(len(words)-1)\n",
    "        ans=\"\"\n",
    "        res=[]\n",
    "        # 空格要平分在几个单词之间，只有平分不了的才放到最后单词后面\n",
    "        for i in range(len(words)-1):\n",
    "            res.append(words[i])\n",
    "            res.append(avg*' ')\n",
    "        res.append(words[-1])\n",
    "        res.append(rest*' ')\n",
    "        return ''.join(res)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        n = text.count(\" \")\n",
    "        words = [word for word in text.split(\" \") if word]\n",
    "        l = len(words)\n",
    "        if l == 1:\n",
    "            return words[0] + n * \" \"\n",
    "        \n",
    "        \n",
    "        return (n // (l - 1) * \" \").join(words) + n % (l - 1) * \" \""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# Review! Got a bunch of WAs, also need to consider O(1) space solution?\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        words, total_len = text.split(), len(text)\n",
    "        word_count, word_char_count = len(words), sum(len(word) for word in words)\n",
    "        space_count = total_len - word_char_count\n",
    "        space_in_middle = (space_count // (word_count - 1)) if word_count > 1 else 0 # 2WA: devide by zero\n",
    "        # space_remaining = space_count - space_in_middle # 1WA\n",
    "        space_remaining = (space_count % (word_count - 1)) if word_count > 1 else space_count\n",
    "        return (\" \" * space_in_middle).join(words) + (\" \" * space_remaining)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        ncnt = text.count(\" \")\n",
    "        s = text.split()\n",
    "        if len(s) == 1:\n",
    "            return \"\".join(s) + \" \" * ncnt\n",
    "        d, m = divmod(ncnt, len(s) - 1)\n",
    "        return (\" \" * d).join(s) + \" \" * m"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        l = text.split()\n",
    "        space = text.count(' ')\n",
    "        if len(l) == 1:\n",
    "            return l[0] + ' ' * space\n",
    "        between, last = divmod(space, (len(l) - 1))\n",
    "        between *= ' '\n",
    "        return (between).join(l) + ' ' * last"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        text_new = text.split()\n",
    "\n",
    "        character_number = 0\n",
    "        for word in text_new:\n",
    "            character_number += len(word)\n",
    "\n",
    "        word_number = len(text_new)\n",
    "        space_number = len(text) - character_number\n",
    "\n",
    "        if word_number == 1:\n",
    "            sentence = text_new[0 ] + \" \" * space_number\n",
    "\n",
    "        else:\n",
    "            neighbor = space_number // (word_number - 1)\n",
    "            rest = space_number % (word_number - 1)\n",
    "\n",
    "            sentence = text_new[0] + \" \" * neighbor\n",
    "            for i in range(1, len(text_new)-1):\n",
    "                sentence += text_new[i] + \" \" * neighbor\n",
    "            sentence = sentence + text_new[-1] + \" \" * rest\n",
    "        \n",
    "        return sentence"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        # 去掉空格，转成列表['this', 'is', 'a', 'sentence']\n",
    "        words=text.split()\n",
    "        # 空格的数量\n",
    "        space=text.count(' ')\n",
    "        # 如果只有一个单词，把空格全加在单词后面就行\n",
    "        if len(words)==1:\n",
    "            return words[0]+\" \"*space\n",
    "        # 如果有多个单词，每个单词平分，多余的放最后\n",
    "        # avg=space//(len(words)-1)\n",
    "        # rest=space%(len(words)-1)\n",
    "        # 被除数，除数，\n",
    "        avg,rest=divmod(space, len(words) - 1)\n",
    "        res=[]\n",
    "        # 空格要平分在几个单词之间，只有平分不了的才放到最后单词后面\n",
    "        for i in range(len(words)-1):\n",
    "            res.append(words[i])\n",
    "            res.append(avg*' ')\n",
    "        res.append(words[-1])\n",
    "        res.append(rest*' ')\n",
    "\n",
    "        return ''.join(res)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        count = 0\n",
    "        for i in text:\n",
    "            if i == \" \":\n",
    "                count += 1\n",
    "        text = text.split(\" \")\n",
    "        temp = []\n",
    "        for i in text:\n",
    "            if i != \"\":\n",
    "                temp.append(i)\n",
    "        if len(temp) == 1:\n",
    "            return temp[0]+\" \"*count\n",
    "        n = count//(len(temp)-1)\n",
    "        print(temp)\n",
    "        res = \"\"\n",
    "        for i in temp:\n",
    "            res += i+\" \"*n\n",
    "        print(res)\n",
    "        res = res[:-n]+\" \"*(count%(len(temp)-1))\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        c = text.count(\" \")\n",
    "        li = text.strip().split()\n",
    "        if len(li) == 1:\n",
    "            return li[0] + \" \" * c\n",
    "        s, s1 = divmod(c, len(li) - 1) \n",
    "        return (\" \" * s).join(li)  + \" \" * s1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        words = text.split()\n",
    "        space = text.count(' ')\n",
    "        if len(words)==1:\n",
    "            return words[0]+' '*space\n",
    "        per_space,rest_space = divmod(space,len(words)-1)\n",
    "        return (' '*per_space).join(words)+' '*rest_space"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        lt=text.split()\n",
    "        ct=0\n",
    "        for i in text:\n",
    "            if i.isspace():\n",
    "                ct+=1\n",
    "        #print(lt)\n",
    "        if len(lt)==1:\n",
    "            t,y=0,ct\n",
    "        else:\n",
    "            t,y=ct//(len(lt)-1),ct%(len(lt)-1)            \n",
    "        a=' ' * t\n",
    "        r=a.join(lt) + ' '*y\n",
    "        return r"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        res = \"\"\n",
    "        count = text.count(' ')\n",
    "        list_str = text.split()\n",
    "        length = len(list_str)\n",
    "        if length == 1:\n",
    "            res = text.strip() + count*' '\n",
    "            return res\n",
    "        a = count // (length-1)\n",
    "        b = count % (length-1)\n",
    "        for i in list_str:\n",
    "            res += i+a*' '\n",
    "        res = res[:-a] + b * ' '\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "import re\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        c=text.count(' ')\n",
    "        pat='\\w+'\n",
    "        cs=re.findall(pat,text)\n",
    "        if len(cs)==1:\n",
    "            return cs[0]+' '*c\n",
    "        avgn=c//(len(cs)-1) #平均空格数\n",
    "        n=c%(len(cs)-1) #末尾空格\n",
    "        return (' '*avgn).join(cs)+' '*n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        blank_number = 0\n",
    "        char_list = [x for x in text.split(' ') if x != '']\n",
    "        character_number = len(char_list)\n",
    "        if character_number != 1:\n",
    "            for i in text:\n",
    "                if i == ' ':\n",
    "                    blank_number += 1\n",
    "            ave_blank, end_blank = divmod(blank_number, character_number-1)\n",
    "            sentence = (' ' * ave_blank).join(char_list) + ' '*end_blank\n",
    "        else:\n",
    "            sentence = ''.join(char_list) + ' ' * (len(text) - len(''.join(char_list)))\n",
    "        return sentence\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        n=text.count(\" \")\n",
    "        words=text.split()\n",
    "        l=len(words)-1\n",
    "        return words[0]+\" \"*n if l==0 else ((n//l)*\" \").join(words)+\" \"*(n%l)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        num = text.count(' ')\n",
    "        l = text.split()\n",
    "        if len(l) > 1:\n",
    "            space = num / (len(l)-1)\n",
    "        else:\n",
    "            space = num\n",
    "        s = ''\n",
    "        for i in l:\n",
    "            s = s + i\n",
    "            if num >= space:\n",
    "                for j in range(int(space)):\n",
    "                    s = s + ' '\n",
    "                    num -=1\n",
    "        if num != 0:\n",
    "            for k in range(num):\n",
    "                s = s +' '\n",
    "\n",
    "        return s "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        return (\" \" * (space // (len(sp) - 1))).join(sp) + \" \" * (space % (len(sp) - 1)) if (space := text.count(\" \")) and len(sp := text.split()) > 1 else (sp[0] + \" \" * space if space else text)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        # danci = []\n",
    "        # count_none = 0\n",
    "        # left = 0\n",
    "        # right = 0\n",
    "        # while right <= len(text)-1:\n",
    "            \n",
    "        #     if text[left] == \" \" and text[right] != \" \":\n",
    "        #         left = right\n",
    "        #     if text[right] == \" \":\n",
    "        #         count_none += 1\n",
    "        #         if right != 0:\n",
    "        #             if text[right-1] != \" \":\n",
    "        #                 if text[left] != \" \":\n",
    "        #                     danci.append(text[left:right])\n",
    "        #                     left = right\n",
    "        #     if right == len(text)-1 and text[right] != \" \":\n",
    "        #         danci.append(text[left:right+1])\n",
    "        #     right += 1\n",
    "        # n = len(danci)\n",
    "        # if n ==1:\n",
    "        #     return ''.join(danci)+count_none*\" \"\n",
    "        # m = count_none//(n-1)\n",
    "        # j = count_none%(n-1)\n",
    "        # ans = []\n",
    "        # for i in range(n):\n",
    "        #     ans.append(danci[i])\n",
    "        #     if i != n-1:\n",
    "        #         ans.append(m*\" \")\n",
    "        #     else:\n",
    "        #         ans.append(j*\" \")\n",
    "        # return ''.join(ans)\n",
    "        count_none = text.count(\" \")\n",
    "        danci = text.strip().split()\n",
    "        if len(danci) == 1:\n",
    "            return danci[0]+\" \"*count_none\n",
    "        i,j = divmod(count_none,len(danci)-1)\n",
    "        return (\" \"*i).join(danci)+\" \"*j\n",
    "        \n",
    "        \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        num = text.count(' ')\n",
    "        l = text.split()\n",
    "        temp = ''\n",
    "        reStr = ''\n",
    "        if len(l) > 1:\n",
    "            space = int(num / (len(l)-1))\n",
    "        else:\n",
    "            space = num\n",
    "        \n",
    "        for i in range(space):\n",
    "            temp = temp + ' '\n",
    "\n",
    "        \n",
    "        for j in l:\n",
    "            reStr = reStr + j\n",
    "            if num >= space:\n",
    "                reStr += temp\n",
    "                num -= space\n",
    "\n",
    "        if num >= 1:\n",
    "            for k in range(num):\n",
    "                reStr = reStr +' '\n",
    "\n",
    "        return reStr "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        words = text.split()\n",
    "        space = text.count(' ')\n",
    "        if len(words) == 1:\n",
    "            return words[0] + ' ' * space\n",
    "        per_space, rest_space = divmod(space, len(words) - 1)\n",
    "        return (' ' * per_space).join(words) + ' ' * rest_space\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        t_list = text.split()\n",
    "        k_len = len(t_list)\n",
    "        k = text.count(' ')\n",
    "        if len(t_list) > 1:\n",
    "            k_len = len(t_list) - 1\n",
    "            k_d = k % k_len\n",
    "            k = k // k_len\n",
    "            return ((' '* k).join(t_list) + ' ' * k_d)\n",
    "        else:\n",
    "            return (t_list[0] + ' ' * k)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution():\n",
    "\n",
    "    def __init__(self):\n",
    "        pass\n",
    "\n",
    "    def reorderSpaces(self, text):\n",
    "        x_list = text.split(' ')\n",
    "        num_word = 0\n",
    "        num_space = 0\n",
    "        word_list = []\n",
    "        result = \"\"\n",
    "\n",
    "        for i in text:\n",
    "            if i == ' ':\n",
    "                num_space += 1\n",
    "\n",
    "        for i in x_list:\n",
    "            if i != '':\n",
    "                word_list.append(i)\n",
    "                num_word += 1\n",
    "\n",
    "        if num_word == 1:\n",
    "            offset = 0\n",
    "        else:\n",
    "            offset = num_space // ( num_word - 1 )\n",
    "\n",
    "        rest = num_space - offset * ( num_word - 1 )\n",
    "\n",
    "        _index = 0\n",
    "        for i in word_list:\n",
    "            _index += 1\n",
    "            result = result + i\n",
    "\n",
    "            if _index == len(word_list):\n",
    "                break\n",
    "\n",
    "            for j in range(offset):\n",
    "                result = result + ' '\n",
    "        \n",
    "        for i in range(rest):\n",
    "            result = result + ' '\n",
    "\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        空格个数 = text.count(\" \")\n",
    "        单词列表 = text.split()\n",
    "        if len(单词列表) == 1:\n",
    "            return 单词列表[0]+\" \"*空格个数\n",
    "        商, 余 = divmod(空格个数, len(单词列表)-1)\n",
    "        return (\" \"*商).join(单词列表) + \" \"*余"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        num = text.count(' ')\n",
    "        l = text.split()\n",
    "        reStr = ''\n",
    "        temp = ''\n",
    "        if num == 0:\n",
    "            return text \n",
    "\n",
    "        if len(l) > 1:\n",
    "            space = int(num / (len(l)-1))\n",
    "        else:\n",
    "            space = num\n",
    "        \n",
    "        for i in range(space):\n",
    "            temp = temp + ' '\n",
    "\n",
    "        \n",
    "        for j in l:\n",
    "            reStr = reStr + j\n",
    "            if num >= space:\n",
    "                reStr += temp\n",
    "                num -= space\n",
    "\n",
    "        if num >= 1:\n",
    "            for k in range(num):\n",
    "                reStr = reStr +' '\n",
    "\n",
    "        return reStr "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        space_cnt = text.count(' ')\n",
    "        text_list = list(filter( lambda x: x, text.split(' ')))\n",
    "        space_cnt2 = len(text_list) - 1\n",
    "        ans = ''\n",
    "        if space_cnt2 > 0:\n",
    "            ans = (' '*(space_cnt//space_cnt2)).join(text_list)\n",
    "            ans += ' ' *(space_cnt%space_cnt2)\n",
    "        else:\n",
    "            ans = text_list[0] + ' ' * space_cnt\n",
    "        return ans\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        n=text.count(\" \")\n",
    "        words=text.split()\n",
    "        l=len(words)-1\n",
    "        return words[0]+\" \"*n if l==0 else ((n//l)*\" \").join(words)+\" \"*(n%l)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        space = text.count(' ')\n",
    "        text = text.split()\n",
    "        if len(text)==1:\n",
    "            return text[0]+' '*space\n",
    "        return (' '*(space//(len(text)-1))).join(text)+' '*(space%(len(text)-1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        blank = 0\n",
    "        words = []\n",
    "        i = 0\n",
    "        n = len(text)\n",
    "        while i < n:\n",
    "            while i < n and text[i] == ' ':\n",
    "                blank += 1\n",
    "                i += 1\n",
    "            pre = i\n",
    "            while i < n and text[i].isalpha():\n",
    "                i += 1\n",
    "            if pre != i:\n",
    "                words.append(text[pre:i])\n",
    "            \n",
    "        # print(blank, words)\n",
    "        if len(words) == 1:\n",
    "            return words[0]+' '*blank\n",
    "        count = (blank)//(len(words)-1)\n",
    "        c = ' '*count\n",
    "        # print(c)\n",
    "        return c.join(words)+' '*(blank%(len(words)-1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        ans = text.count(\" \")\n",
    "        text = text.split()\n",
    "        if len(text) == 1:\n",
    "            return text[0] + \" \" * ans\n",
    "        a, b = divmod(ans, len(text) - 1)\n",
    "        return (\" \" * a).join(text) + \" \" * b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        # 去掉空格，转成列表['this', 'is', 'a', 'sentence']\n",
    "        words=text.split()\n",
    "        # 空格的数量\n",
    "        space=text.count(' ')\n",
    "        # 如果只有一个单词，把空格全加在单词后面就行\n",
    "        if len(words)==1:\n",
    "            return words[0]+\" \"*space\n",
    "        # 如果有多个单词，每个单词平分，多余的放最后\n",
    "        # avg=space//(len(words)-1)\n",
    "        # rest=space%(len(words)-1)\n",
    "        # 被除数，除数，\n",
    "        avg,rest=divmod(space, len(words) - 1)\n",
    "        ans=\"\"\n",
    "        res=[]\n",
    "        # 空格要平分在几个单词之间，只有平分不了的才放到最后单词后面\n",
    "        for i in range(len(words)-1):\n",
    "            res.append(words[i])\n",
    "            res.append(avg*' ')\n",
    "        res.append(words[-1])\n",
    "        res.append(rest*' ')\n",
    "\n",
    "        return ''.join(res)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        sep = ' '\n",
    "        words = text.split()\n",
    "        cnt = len(words)\n",
    "        spaces = text.count(sep)\n",
    "        sep_num = spaces // (cnt - 1)  if cnt >= 2 else 0\n",
    "        return (sep * sep_num).join(words) + sep * (spaces - sep_num * (cnt - 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        lst = []\n",
    "        i, j = 0, 0\n",
    "        c = 0\n",
    "        while j < len(text):\n",
    "            if text[j] == \" \":\n",
    "                if text[i] != \" \":\n",
    "                    lst.append(text[i: j])\n",
    "                    i = j\n",
    "                c += 1\n",
    "            else:\n",
    "                if text[i] == \" \":\n",
    "                    i = j\n",
    "            j += 1\n",
    "        if text[i] != \" \":\n",
    "            lst.append(text[i: j])\n",
    "        n = len(lst) - 1\n",
    "        if n == 0:\n",
    "            return lst[0] + \" \" * c\n",
    "        else:\n",
    "            a, b = c // n, c % n\n",
    "            return (\" \" * a).join(lst) + \" \" * b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        words = text.split()\n",
    "        blank = text.count(' ')\n",
    "        # 计算每个单词之间的空格数和剩余的空格数\n",
    "        if len(words) > 1:\n",
    "            space, rest = divmod(blank, len(words) - 1)\n",
    "        else:\n",
    "            space, rest = 0, blank\n",
    "        # 使用空格连接单词，并在末尾添加剩余的空格\n",
    "        res = (space * ' ').join(words) + rest * ' '\n",
    "        return res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        spaces = 0\n",
    "        n = 0\n",
    "        words = text.split(\" \")\n",
    "        newwords = []\n",
    "\n",
    "        for w in words:\n",
    "            if w.isalpha():\n",
    "                n += 1\n",
    "                newwords.append(w)\n",
    "        for i in text:\n",
    "            if i == \" \":\n",
    "                spaces += 1\n",
    "        if n == 1:\n",
    "            return newwords[0] + \" \"*spaces\n",
    "        avg = spaces//(n-1)\n",
    "        end = spaces%(n-1)\n",
    "\n",
    "        return (\" \"*avg).join(newwords)+\" \"*end\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        words=text.split()\n",
    "        space=text.count(' ')\n",
    "        if len(words)==1:\n",
    "            return words[0]+' '*space\n",
    "        per_space=space//(len(words)-1)\n",
    "        res_space=space%(len(words)-1)\n",
    "        return (' '*per_space).join(words)+' '*res_space"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        num = text.count(' ')\n",
    "        print(num)\n",
    "\n",
    "        texts = [item for item in text.split(' ') if len(item) > 0]\n",
    "        print(texts)\n",
    "\n",
    "        if len(texts) > 1:\n",
    "            m = num // (len(texts) -1)\n",
    "            n = num % (len(texts) -1) \n",
    "        else:\n",
    "            m = 0\n",
    "            n = num\n",
    "\n",
    "        return (' ' * m).join(texts) + ' ' * n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        count = 0\n",
    "        for i in range(len(text)):\n",
    "            if text[i]==\" \":\n",
    "                count = count+1\n",
    "        text1 = text.strip()\n",
    "        lst = text1.split()\n",
    "        length = len(lst)\n",
    "        if length==1:\n",
    "            return lst[0]+\" \"*count\n",
    "        num = count//(length-1)\n",
    "        yu = count%(length-1)\n",
    "        res = \"\"\n",
    "        for i in range(length-1):\n",
    "            res = res+lst[i]+\" \"*num\n",
    "        res = res+lst[-1]+yu*\" \"\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        n = text.count(' ')\n",
    "        words =text.split()\n",
    "        l = len(words)\n",
    "        r = ''\n",
    "        if l == 1:\n",
    "            r = words[0] + ' ' * n\n",
    "        else:\n",
    "            t = n // (l - 1)\n",
    "            s = n % (l - 1)\n",
    "            r = (' ' * t).join(words) + ' ' * s\n",
    "        return r\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        c = text.count(\" \")\n",
    "        words = [s for s in text.split(\" \") if s]\n",
    "        n = len(words) - 1\n",
    "        if n == 0:\n",
    "            return words[0] + \" \" * c\n",
    "        else:\n",
    "            a, b = c // n, c % n\n",
    "            return (\" \" * a).join(words) + \" \" * b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        words, total_len = text.split(), len(text)\n",
    "        word_count, word_char_count = len(words), sum(len(word) for word in words)\n",
    "        space_count = total_len - word_char_count\n",
    "        space_in_middle = (space_count // (word_count - 1)) if word_count > 1 else 0 # 2WA: devide by zero\n",
    "        # space_remaining = space_count - space_in_middle # 1WA\n",
    "        space_remaining = (space_count % (word_count - 1)) if word_count > 1 else space_count\n",
    "        return (\" \" * space_in_middle).join(words) + (\" \" * space_remaining)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        s=0\n",
    "        for i in text:\n",
    "            if i==\" \":\n",
    "                s+=1\n",
    "        arr=text.split()\n",
    "        cnt=len(arr)-1\n",
    "        if cnt==-1:\n",
    "            return text\n",
    "        if cnt==0:\n",
    "            return arr[0]+\" \"*s\n",
    "        return (\" \"*(s//cnt)).join(arr)+\" \"*(s%cnt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        l1 = []\n",
    "        count = 0\n",
    "        text = \" \" + text + \" \"\n",
    "        x = \"\"\n",
    "        for i in range (1, len(text) - 1):\n",
    "            if text[i] == \" \":\n",
    "                count += 1\n",
    "            else:\n",
    "                x += text[i]\n",
    "            if text[i] == \" \" and x != \"\":\n",
    "                l1.append(x)\n",
    "                x = \"\"\n",
    "        if x != \"\":\n",
    "            l1.append(x)\n",
    "        if len(l1) == 1:\n",
    "            return l1[0] + count * \" \"\n",
    "        elif len(l1) == 2:\n",
    "            return l1[0] + count * \" \" + l1[1]\n",
    "        else:\n",
    "            y = count // (len(l1) - 1)\n",
    "            yu = count - y * (len(l1) - 1)\n",
    "            target = \"\"\n",
    "            for i in range (len(l1) - 1):\n",
    "                target += l1[i] + \" \" * y\n",
    "            return target + l1[-1] + yu * \" \""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        null = text.count(\" \")\n",
    "        lst = [ls for ls in text.split(\" \") if ls]\n",
    "        m = len(lst)\n",
    "        if m == 1:\n",
    "            return lst[0] + \" \"*null\n",
    "        \n",
    "        cut = \" \"*(null//(m-1))\n",
    "        return cut.join(lst) + \" \"*(null%(m-1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        c = text.count(\" \")\n",
    "        lst = text.split(\" \")\n",
    "        words = [s for s in lst if s]\n",
    "        n = len(words) - 1\n",
    "        if n == 0:\n",
    "            return words[0] + \" \" * c\n",
    "        a, b = c // n, c % n\n",
    "        return (\" \" * a).join(words) + \" \" * b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "import re\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        c=text.count(' ')\n",
    "        pat='\\w+'\n",
    "        cs=re.findall(pat,text)\n",
    "        if len(cs)==1:                  #一个单词没空格的情况\n",
    "            return cs[0]+' '*c\n",
    "        avgn=c//(len(cs)-1)             #平均空格数\n",
    "        n=c%(len(cs)-1)                 #末尾空格\n",
    "        return (' '*avgn).join(cs)+' '*n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        s,t,f=0,0,0\n",
    "        words=[]\n",
    "        word=''\n",
    "        for i in text:\n",
    "            if i==' ':\n",
    "                s+=1\n",
    "                if word:\n",
    "                    words.append(word)\n",
    "                word=''\n",
    "                f=0\n",
    "            if 'a'<=i<='z':\n",
    "                if f==0:\n",
    "                    t+=1\n",
    "                    f=1\n",
    "                word+=i\n",
    "        if word:\n",
    "            words.append(word)\n",
    "        if t==1:\n",
    "            return words[0]+' '*s\n",
    "        n=s//(t-1)\n",
    "        m=s%(t-1)\n",
    "        ans=words[0]\n",
    "        if len(words)==1:\n",
    "            return ans+' '*m\n",
    "        for i in words[1::]:\n",
    "            ans+=' '*n\n",
    "            ans+=i\n",
    "        return ans+' '*m"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        words = text.split()\n",
    "        space = text.count(\" \")\n",
    "        if len(words) == 1:\n",
    "            return words[0] + \" \" * space\n",
    "        per_space, rest_space = divmod(space, len(words) - 1)\n",
    "        return (' ' * per_space).join(words) + ' ' * rest_space\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        space = 0\n",
    "        word = []\n",
    "        for i in text:\n",
    "            if i == ' ':\n",
    "                space += 1\n",
    "        for i in text.split(' '):\n",
    "            if i:\n",
    "                word.append(i)\n",
    "        if len(word) == 1:\n",
    "            return word[0] + ' '*space\n",
    "        else:\n",
    "            a = space//(len(word)-1)\n",
    "            b = ' '*a\n",
    "            c = ' '*(space%(len(word)-1))\n",
    "            return b.join(word) + c\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        tmp = text.split()\n",
    "        s = 0\n",
    "        for t in tmp:\n",
    "            s += len(t)\n",
    "        os = len(text)\n",
    "        kg = 0\n",
    "        if len(tmp) <= 1 :\n",
    "            kgs = ''\n",
    "            okg = ' ' * (os -s)\n",
    "        else:\n",
    "            kg = math.floor((os - s) / (len(tmp) - 1 ))\n",
    "            okg = (os - s) % (len(tmp) - 1 )\n",
    "            kgs = ' ' * kg\n",
    "            okg = ' ' * okg\n",
    "        return kgs.join(tmp) + okg\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        arr = [x for x in text.split(' ') if x]\n",
    "        n, m = (0, text.count(' ')) if len(arr) == 1 else divmod(text.count(' '), len(arr) - 1)\n",
    "        print(n, m)\n",
    "        return (' ' * n).join(arr) + ' ' * m\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "      aa=text.count(' ')\n",
    "      bb=text.split()\n",
    "\n",
    "      if len(bb)==1:\n",
    "        return ''.join(bb)+' '*aa\n",
    "\n",
    "      zz=aa//(len(bb)-1)\n",
    "      zzz=aa%(len(bb)-1)\n",
    "      \n",
    "      result=''.join(bb[0])\n",
    "      for i in range(len(bb)):\n",
    "        word=''.join(bb[i])\n",
    "        if i!=0:\n",
    "          result+=' '*zz+word\n",
    "      result+=' '*zzz\n",
    "      return result\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        n = text.count(' ')\n",
    "        #print(n)\n",
    "        text_lst = text.strip().split()\n",
    "        text_res = []\n",
    "        for x in text_lst:\n",
    "            if x != ' ':\n",
    "                text_res.append(x)\n",
    "        if len(text_res) == 1:\n",
    "            return text_res[0] + ' ' * n\n",
    "\n",
    "        sp_avg = n//(len(text_res) - 1)\n",
    "        sp_rest = n%(len(text_res) - 1)\n",
    "    \n",
    "\n",
    "        res = []\n",
    "        for i in range(len(text_res)):\n",
    "            res.append(text_res[i])\n",
    "\n",
    "            if i != len(text_res) - 1:\n",
    "                res.append(' '*sp_avg)\n",
    "            else:\n",
    "                res.append(' '*sp_rest)\n",
    "        return ''.join(res)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        spaceLen=text.count(' ')\n",
    "        word_list=text.split()\n",
    "        if len(word_list) == 1:\n",
    "            return word_list[0] + spaceLen*' '\n",
    "        ans=word_list[0]\n",
    "        for i in word_list[1:]:\n",
    "            ans+=spaceLen//(len(word_list)-1)*' '\n",
    "            ans+=i\n",
    "        if spaceLen%(len(word_list)-1) != 0:\n",
    "            ans+=spaceLen%(len(word_list)-1)*' '\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reorderSpaces(self, text: str) -> str:\n",
    "        s = text.split()\n",
    "        if len(s) == 1: return \"\".join(s) + (len(text) - len(s[0])) * \" \"\n",
    "        space_count = len(text) - sum(len(word) for word in s)  # 原字符串的空格总数\n",
    "        fill_count = space_count // (len(s) - 1)  # 字符串中单词间应添加的空格数\n",
    "        tail_count = space_count % (len(s) - 1)  # 字符串尾部应添加的空格数\n",
    "        ans = \"\"\n",
    "        for i in range(len(s) - 1): ans += \"\".join(s[i]) + \" \" * fill_count\n",
    "        return ans + \"\".join(s[-1]) + \" \" * tail_count"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}
